package com.jintoufs.service.security.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.cosmos.modules.utils.reflection.ConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jintoufs.domain.security.Resource;
import com.jintoufs.service.role.RoleService;
import com.jintoufs.service.security.AuthorizationService;
import com.jintoufs.service.security.ResourceService;

@Service("authorizationService")
public class AuthorizationServiceImpl implements AuthorizationService {

	private ResourceService resourceService;

	@Override
	public void grant(Integer roleId, String resourceIds) {
		resourceService.deleteResourceByRole(roleId);
		batchSaveRoleResource(roleId, resourceIds);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<String> obtainAuthorityCodes(Integer roleId) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("roleId", roleId);
		List<Resource> resources = resourceService.findByParams(params);

		return ConvertUtils.convertElementPropertyToList(resources, "resourceCode");
	}

	public boolean isPermitted(Integer roleId, Integer resourceId) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("roleId", roleId);
		List<Resource> resources = resourceService.findByParams(params);
		return containsResource(resources, resourceId);
	}

	private boolean containsResource(List<Resource> srcList, Integer destResourceId) {
		for (Resource src : srcList) {
			Integer srcResourceId = src.getId();
			if (destResourceId.intValue() == srcResourceId.intValue()) {
				return true;
			}
		}
		return false;
	}

	private void batchSaveRoleResource(Integer roleId, String resourceIds) {
		if (StringUtils.isNotEmpty(resourceIds)) {
			String[] resourceCodeArray = StringUtils.split(resourceIds, ",");
			for (String resourceId : resourceCodeArray) {
				Integer id = Integer.parseInt(resourceId);
				resourceService.saveRoleResource(roleId, id);
			}
		}
	}

	@Autowired
	public void setRoleService(RoleService roleService) {
	}

	@Autowired
	public void setResourceService(ResourceService resourceService) {
		this.resourceService = resourceService;
	}

}
